from django.shortcuts import render

# Create your views here.


import requests, time, hashlib, base64, hmac, json
import urllib.parse, os


class FeiShu_WebHook:

    def __init__(self, secret="l854gG4A7jrRdzHtM5O3uc"):
        # self.timestamp = timestamp
        self.secret = secret

    # @staticmethod
    def gen_sign(self):
        # 拼接timestamp和secret
        string_to_sign = '{}\n{}'.format(int(time.time()), self.secret)
        hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()

        # 对结果进行base64处理
        sign = base64.b64encode(hmac_code).decode('utf-8')

        return sign

    def send_text(self, sign, log):
        url = "https://open.feishu.cn/open-apis/bot/v2/hook/90bdd4a0-4910-4f80-9bc3-8c75d180fe48"
        headers = {'Content-Type': 'application/json;charset=UTF-8'}
        request_param = {
            "timestamp": "%s" % (int(time.time())),
            "sign": "%s" % (sign),
            "msg_type": "text",
            "content": {
                "text": "%s" % (log)
            }
        }
        response = requests.post(url, data=json.dumps(request_param), headers=headers)


def FsLog(msg):
    h = FeiShu_WebHook("l854gG4A7jrRdzHtM5O3uc")
    h.send_text(h.gen_sign(), msg)


def ElMessage(msg=None, data=None, type="info"):
    data = {
        "type": type,
        "message": msg,
        "data": data,
        "center": True,
        "duration": 8000,
        "show-close": True
    }

    return data


class DingDingMessage:
    def __init__(self, access_token, secret_key="<KEY>"):
        self.access_token = access_token
        self.secret_key = secret_key

    def gen_sign(self):
        timestamp = str(round(time.time() * 1000))
        secret = self.secret_key
        secret_enc = secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(timestamp, secret)
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        # print(timestamp)
        # print(sign)
        return timestamp, sign

    def send_text(self, msg):
        timestamp, sign = self.gen_sign()
        url = f"https://oapi.dingtalk.com/robot/send?access_token={self.access_token}&timestamp={timestamp}&sign={sign}"
        headers = {'Content-Type': 'application/json;charset=UTF-8'}
        request_param = {
            "msgtype": "text",
            "text": {
                "content": msg
            },
        }
        try:
            response = requests.post(url, data=json.dumps(request_param), headers=headers)
        except Exception as e:
            FsLog(e)

def ddSend():
    # dd = DingDingMessage("bbeb8d4beaaa35c780016cc06c4724eeea5888efcc232903e20e331de7104787","SEC84ddcec6e608c10e9cced5bb3299173af36dfea0d37655055509188a9faa61e1")
    dd = DingDingMessage(os.getenv("DD_ACCESS_TOKEN",default="bbeb8d4beaaa35c780016cc06c4724eeea5888efcc232903e20e331de7104787"), os.getenv("DD_SECRET_KEY",default="SEC84ddcec6e608c10e9cced5bb3299173af36dfea0d37655055509188a9faa61e1"))
    # print("DD_ACCESS_TOKEN:", dd.access_token, "DD_SECRET_KEY:", dd.secret_key)
    return dd

